﻿using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace MetaDrive.Edmx
{   
    public class EdmxFile
    {
        private XDocument doc;

        public Conceptual.Schema Conceptual { get; private set; }
        public Mapping.Mapping Mapping { get; private set; }

        public EdmxFile(string fileName)
        {
            XNamespace edmxns = EdmxConstants.EDMX_NAMESPACE_V2;
            XNamespace ssdlns = EdmxConstants.SSDL_NAMESPACE_V2;
            XNamespace csdlns = EdmxConstants.CSDL_NAMESPACE_V2;
            XNamespace mslns = EdmxConstants.MSL_NAMESPACE_V2;

            doc = XDocument.Load(fileName);
            XElement edmxNode = doc.Element(edmxns + "Edmx");
            XElement runtimeNode = edmxNode.Element(edmxns + "Runtime");

            XElement ssdlnode = runtimeNode.Element(edmxns + "Store");
            XElement csdlnode = runtimeNode.Element(edmxns + "Conceptual");
            XElement mslnode = runtimeNode.Element(edmxns + "Mapping");

            XElement ssdlcon = ssdlnode.Element(ssdlns + "Schema");    
            XElement csdlcon = csdlnode.Element(csdlns + "Schema");
            XElement mslcon = mslnode.Element(mslns + "Mapping");

            var conceptualSerializer = new XmlSerializer(typeof(Conceptual.Schema));
            Conceptual = (Conceptual.Schema)conceptualSerializer.Deserialize(new StringReader(csdlcon.ToString()));

            var Mappingerializer = new XmlSerializer(typeof(Mapping.Mapping));
            Mapping = (Mapping.Mapping)Mappingerializer.Deserialize(new StringReader(mslcon.ToString()));
        }
    }
}
